/**
 * Created By zhangQ 2018/4/13
 * [打印控件封装]
 */
import Vue from 'vue'
import moment from 'moment'
import uuid from 'uuid'
import { findLodop } from './lodop'
import axiosUtils from '@api/env/axiosEnv'
import config from '../../../config'

let customAxios = axiosUtils._initAxios()

let templatePrefix = 'static/template/'
let templateBaseUrl = process.env.NODE_ENV !== 'production' ? ('http://' + config.dev.host + ':' + config.dev.port + '/' + templatePrefix) : templatePrefix
console.log(templateBaseUrl)
let printUtils = {
  invoke () {
  },
  print (datas) {
    findLodop().then((lodop) => {
      let config = Object.assign({}, datas)
      try {
        if (!(lodop && lodop.VERSION)) {
          console.error('找不到lodop')
          return
        }
      } catch (err) {
      }
      lodop.PRINT_INIT(config.title)
      lodop.SET_PRINT_PAGESIZE(0, config.width, config.height, 'CreateCustomPage')
      lodop.ADD_PRINT_HTM(0, 0, config.width, config.height, config.template)
      lodop.SET_PREVIEW_WINDOW(0, 0, 1, 800, 600, config.title)
      lodop.SET_SHOW_MODE('PREVIEW_NO_MINIMIZE', true)// 预览窗口禁止最小化，并始终最前
      lodop.PREVIEW()
    })
  },
  /**
   * ajax获得模板路径
   * @auther zhangQ
   * @date 2018/4/20 18:40
   */
  getTemplateForAjax (template) {
    return new Promise((resolve, reject) => {
      customAxios({
        url: '/getPrintTemplate?time=' + Date.now(),
        data: { templatePath: __dirname },
        method: 'get'
      }).then((res) => {
        if (+res.data.isSuccess !== 1) {
          reject(new Error('未找到模板'))
        } else if (+res.data.isSuccess === 1) {
          console.log('模板路径：', templatePrefix + template + '.html')
          let printConf = {}
          let printHtml = ''
          let templateHtml = $(res.data.data)
          for (let i = 0; i < templateHtml.length; i++) {
            if (templateHtml[i].nodeName === 'jsonConfig') {
              printConf = JSON.parse(templateHtml[i].innerHTML.replace(/^\s+|\s+$/g, ''))
            }
            if (templateHtml[i].nodeName === 'body') {
              printHtml = templateHtml[i].innerHTML.replace(/^\s+|\s+$/g, '')
            }
          }
          resolve({ printConf, printHtml })
        }
      }).catch((err) => {
        reject(err)
      })
    })
  },
  /**
   * TODO(渲染打印模板)
   * @auther zhangQ
   * @date 2018/4/20 18:55
   */
  renderPrintPage () {
    let id = 'printdiv' + uuid.v4()
    $('<div id="' + id + '" style="display:none"></div>').appendTo(document.body)
    this.initVue(id).then((vm) => {
      // vm
    })
  },
  /**
   * 实例化模板vue
   * @auther zhangQ
   * @date 2018/4/20 18:45
   */
  initVue (id, template, datas) {
    return new Promise((resolve, reject) => {
      if (typeof datas !== 'object') {
        reject(new Error('数据源必须是对象'))
      }
      let vm = new Vue({
        template: '<div v-el:printtable>' + template + '</div>',
        el: '#' + id,
        data: datas,
        methods: {
          formatTime (val, gs) {
            return moment(val).format(gs)
          }
        },
        created () {
        }
      })
      resolve(vm)
    })
  }
}

export default printUtils
